package com.icezzz.freemarker_demo;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;

/**
 * freemarker demo!
 *
 */
public class App {
    public static void main(String[] args) {
        System.out.println("freemarker demo!");
        Configuration conf = new Configuration(Configuration.VERSION_2_3_30);
        File dir = new File("./target/classes");
        String ftlName = "hello.ftl";
        try {
            conf.setDirectoryForTemplateLoading(dir);
            Template template = conf.getTemplate(ftlName, "UTF-8");
            String outName = simpleName(ftlName);
            Writer writer = new FileWriter(dir + "/" + outName);
            Map<String, Object> dataModel = genData();
            template.process(dataModel, writer);
            writer.flush();
            writer.close();
        } catch (TemplateNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedTemplateNameException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }

    private static Map<String, Object> genData() {
        Map<String, Object> dataModel = new HashMap<String, Object>();
        dataModel.put("hello", "demo");
        dataModel.put("date", new Date());
        return dataModel;
    }

    private static String simpleName(String ftlName) {
        if (ftlName == null || "".equals(ftlName)) {
            return null;
        }
        int lastIndexOf = ftlName.lastIndexOf(".");
        if (lastIndexOf == -1) {
            return ftlName;
        }
        return ftlName.substring(0, lastIndexOf);
    }
}
